package com.sgai.zero_robot.base;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

public class BaseApplication {
    private static final String TAG = "BaseApplication";
    private static final boolean DEBUG = false; // 根据构建类型控制日志

    // 使用线程安全的集合（生命周期回调在主线程，但防止遍历时修改）
    private final List<Activity> activities = new CopyOnWriteArrayList<>();
    private volatile Activity currentActivity; // volatile保证可见性
    private static Application application;
    private final AtomicInteger resumedActivities = new AtomicInteger(0); // 前台Activity计数器

    // 单例模式
    private static class Holder {
        private static final BaseApplication INSTANCE = new BaseApplication();
    }

    public static BaseApplication getInstance() {
        return Holder.INSTANCE;
    }

    private BaseApplication() {}

    public void initBaseApplication(Application app) {
        if (application == null) {
            application = app;
            registerActivityLifecycle();
        }
    }

    private void registerActivityLifecycle() {
        application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
                if (DEBUG) Log.d(TAG, "onActivityCreated: " + activity.getClass().getSimpleName());
                activities.add(activity);
            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {
                if (DEBUG) Log.d(TAG, "onActivityStarted: " + activity.getClass().getSimpleName());
                currentActivity = activity;
            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {
                if (DEBUG) Log.d(TAG, "onActivityResumed: " + activity.getClass().getSimpleName());
                currentActivity = activity;
                resumedActivities.incrementAndGet(); // 增加前台计数
            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {
                if (DEBUG) Log.d(TAG, "onActivityPaused: " + activity.getClass().getSimpleName());
                resumedActivities.decrementAndGet(); // 减少前台计数
            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {
                if (DEBUG) Log.d(TAG, "onActivityStopped: " + activity.getClass().getSimpleName());
                // 如果当前Activity是正在停止的Activity，且没有其他Activity在前台，则置空
                if (currentActivity == activity && resumedActivities.get() == 0) {
                    currentActivity = null;
                }
            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
                if (DEBUG) Log.d(TAG, "onActivitySaveInstanceState: " + activity.getClass().getSimpleName());
            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
                if (DEBUG) Log.d(TAG, "onActivityDestroyed: " + activity.getClass().getSimpleName());
                activities.remove(activity);
                if (currentActivity == activity) {
                    currentActivity = null;
                }
            }
        });
    }

    public static Application getApplication() {
        if (application == null) {
            throw new IllegalStateException("BaseApplication not initialized!");
        }
        return application;
    }

    public Activity getCurrentActivity() {
        return currentActivity;
    }

    /**
     * 判断应用是否在前台
     */
    public boolean isAppInForeground() {
        return resumedActivities.get() > 0;
    }

    /**
     * 安全退出程序
     */
    public void quitApp() {
        // 创建副本避免并发修改
        List<Activity> activityList = new ArrayList<>(activities);
        for (Activity activity : activityList) {
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
        activities.clear();
        // 不推荐直接调用System.exit，让系统管理进程生命周期
        // System.exit(0);
    }
}